package com.bulletelc.apollopre.module.main.center.orders.orderComment;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderItemCommentBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by CX on 2018/2/2.
 */

public class FinishCommentPresenter extends BasePresenter<FinishCommentContract.View> implements FinishCommentContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getOrderDetail(String orderId) {
        getDetail(orderId);
    }

    @Override
    public void postComment(String json) {
        commitComment(json);
    }

    private void getDetail(String orderId) {
        OkGo.<String>post(NetWorkPath.POST_ORDER_DETAIL+"?id="+orderId)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseGetDetail(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorGetOrderDetail(response.getException().toString());
                        }
                    }
                });
    }

    private void parseGetDetail(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    JSONObject objData = new JSONObject(object.getString("data"));
                    JSONArray arrSub = objData.getJSONArray("sales_order_items");
                    List<OrderItemCommentBean> oicList = new ArrayList<>();
                    for (int i = 0; i < arrSub.length(); i++) {
                        OrderItemCommentBean oic = new OrderItemCommentBean();
                        oic.setOrderId(arrSub.getJSONObject(i).getString("order_item_id"));
                        oic.setGoodId(arrSub.getJSONObject(i).getInt("product_id"));
                        oic.setGoodSkuId(arrSub.getJSONObject(i).getString("product_sku_id"));
                        oic.setGoodName(arrSub.getJSONObject(i).getString("product_name"));
                        oic.setGoodSkuName(arrSub.getJSONObject(i).getString("sku_label"));
                        oic.setGoodPrice((float) arrSub.getJSONObject(i).getDouble("sale_price"));
                        oic.setGoodQuantity(arrSub.getJSONObject(i).getInt("quantity"));
                        JSONObject objImg = new JSONObject(arrSub.getJSONObject(i).getString("product_images"));
                        oic.setGoodPic(objImg.getString("medium"));
                        oicList.add(oic);
                    }
//                    OrderItemCommentBean oic = new OrderItemCommentBean();
//                    oicList.add(oic);
                    if (isViewAttached()) {
                        getView().onSuccessGetOrderDetail(oicList);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailGetOrderDetail(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorGetOrderDetail("数据解析有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailGetOrderDetail(response.body().toString());
            }
        }
    }

    private void commitComment(String json) {
        RequestBody body=RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON),json);
        OkGo.<String>post(NetWorkPath.POST_SUBMIT_ORDER_COMMENT)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseSubmitComment(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorPostComment(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析提交评论返回数据
     * @param response
     */
    private void parseSubmitComment(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject object = new org.json.JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessPostComment();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailPostComment(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorPostComment("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailPostComment(response.body().toString());
            }
        }
    }
}
